 <template>
  <el-dialog
    :title="`${title}【${title1}】【${title2}】考核评价清单`"
    :visible.sync="visible"
    width="1600px"
    custom-class="scrollable-dialog"
    :close-on-click-modal="false"
  >
    <el-form ref="formInline" label-width="90px" size="small" label-position="left" :model="formInline">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="供应商名称">
             <el-select v-model="formInline.supplierId" :disabled="isSupplierDisabled" style="width: 100%;" @change="supplierChnage" filterable placeholder="支持模糊搜索">
                <el-option
                  v-for="item in supplierOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="类别名称">
            <el-cascader
    v-model="formInline.supplierStoreId"
    style="width: 100%;"
    @change="typeChange"
    :options="typeTree"></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="考核周期">
            <el-date-picker
                v-model="formInline.time"
                type="daterange"
                style="width: 100%;"
                range-separator="至"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
                </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
          <el-col :span="8">
           <el-form-item label="附件">
               <el-upload
                class="avatar-uploader"
                accept="image/*,application/pdf"
                list-type="picture"
                :on-preview="handlePreview"
                :file-list="fileList"
                :on-remove="handleRemove"
                :before-upload="beforeAvatarUpload"
                action="#"
                :http-request="onChangeFile"
              >
                  <el-button type="primary" size="mini">上传</el-button>
                  <div slot="tip" style="display: inline-block;margin-left: 20px;" class="el-upload__tip">支持图片和pdf</div>
              </el-upload>
           </el-form-item>
        </el-col>
      </el-row>
    </el-form>

     <table class="custom-other-table">
      <tr>
          <td class="tr-title f1">序号</td>
          <td class="tr-title" colspan="2">行为描述</td>
           <td class="tr-title f3">扣分</td>
           <td class="tr-title f4">扣分依据</td>
        </tr>
        <tr v-for="(item,index) in list" :key="index">
          <td align="center">{{ item.i }}</td>
          <td class="tr-title f2" v-if="index === 0" rowspan="4">投标过程</td>
          <td>{{item.title}}</td>
          <td><el-input size="mini" v-model="item.value"/></td>
          <td><el-input type="textarea" autosize size="mini" v-model="item.merkts"/></td>
        </tr>
    </table>


    <div class="columns-container">
      <!-- 固定列 1 -->
      <div class="column fixed-column column1">
        <div class="column-header">序号</div>
        <div class="column1-content" v-for="(item,index) in list2" :key="index">{{ item.i }}</div>
        <div class="column-footer"></div>
      </div>
      
      <!-- 固定列 2 -->
      <div class="column fixed-column column2">
        <div class="column-header">行为描述</div>
        <div class="column-contentp-rowspan">
          <ul class="col1">
            <li>履约过程</li>
            <li>廉洁</li>
            <li>综合评价</li>
          </ul>
          <ul class="col2">
            <li v-for="(item,index) in list2" :key="index" v-html="item.title"></li>
          </ul>
        </div>
        <div class="column-footer">小计</div>
      </div>
      
      <div class="column-box" ref="dynamicColumn">
           
          <div class="column dynamic-column" v-for="(items,colIndex) in projectList" :key="colIndex">
            <div class="column-header">
              <div class="dynamic-header">
                <el-select v-model="items.id" filterable size="mini" placeholder="请选择">
                    <el-option
                      v-for="item in projectOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                  <label class="line">扣分
                    <i class="el-icon-circle-close btns" v-if="projectList.length > 1"  @click="delProject(colIndex,items.prop)"></i>
                  </label>
              </div>
            </div>
            <ul class="dynamic-content">
              <li v-for="(item,index) in list2" :key="index">
                 <input
                    v-model="item[items.prop]"
                    type="text"
                    class="sumot-input"
                    placeholder=""
                    @input="function(e){return calculateTotal(e,colIndex)}"
                  />
              </li>
            </ul>
            <div class="column-footer">
              {{ items.tdScore }}
            </div>
          </div>
      </div>

      <!-- 固定列 3 -->
      <div class="column fixed-column column3">
        <div class="column-header">扣分依据</div>
        <div class="column3-content" v-for="(item,index) in list2" :key="index">
          <el-input type="textarea" placeholder="扣分依据" autosize size="mini" v-model="item.merkts"/>
        </div>
        <div class="column-footer"></div>
      </div>
    </div>



    <el-alert
    title="温馨提示"
    style="margin-top: 10px;"
    type="error">
      <p>扣分等于5分，给予警告，并暂停3个月的投标资格</p>
      <p>扣分达到5-10（不包含10）分，暂停3个月供应商库；</p>
      <p>扣分达到10-20（不含20）分，暂停1年供应商库；</p>
      <p>扣分达20分的或因供应商原因出现廉洁、安全问题的，移出供应商库并在3年内不得入库，具体由招采部填写《供应商调整审批表》报部门分管领导批准后执行。符合《泸州老窖集团黑名单管理办法》相关条款的，按管理办法执行。</p>
     </el-alert>



    <div slot="footer" class="dialog-footer">
       <el-button size="small" type="primary" style="margin-right: 30px;" @click="addDynamicColumn"
        >新增项目</el-button
      >
      <el-button size="small" @click="visible = false"
        >取 消</el-button
      >
      <el-button size="small" type="primary" @click="submitAddly('storeForm')"
        >提交</el-button
      >
    </div>


     <el-dialog title="图片预览" :visible.sync="dialogVisible" append-to-body>
      <img :src="previewUrl" alt="图片预览" class="previcew-img" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

  </el-dialog>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import moment from "moment";
import { getProjectOptions } from '@/api/project_api'
import { getSupplierStorePage,getSupplierEvaluationPage,getSupplierCategoryTree,getEvaluationSave } from "@/api/supplier_api";
import { evaluateUpperList, evaluateUpperList2, evaluateLowerList, evaluateLowerList2 } from "./config"
import { TreeArrar } from '@/utils/index'
import pdfimg from "@/assets/pdf_file.png";
import Big from 'big.js';
export default {
  data() {
    return {
      visible: false,
      dialogVisible: false,
      previewUrl:'',
      title: "",
      title1: "供应商",
      title2:"类别名称",
      formInline: {
        id:'',
        supplierId: '',
        supplierStoreId:'',
        categoryName: '',
        supplierCategory:'',
        time: []
      },
      fileList:[],
      list: [],
      list2: [],
      supplierOptions: [],
      typeTree: [],
      projectOptions: [],
      treeData:[],
      projectList: [],
    };
  },
  computed: {
    isSupplierDisabled() {
      return this.formInline.id ? true : false
    }    
  },
  watch: {
    projectList: {
      handler(arr) {
        if (arr && arr.length >= 4) {
           this.checkContentWidth()
        }
      },
      deep: true,
      immediate:true
    }
  },
  methods: {
     ...mapActions({
      uploadFile: "user/uploadFile"
     }),
    checkContentWidth() {
      this.$nextTick(() => {
         const contentElement = this.$refs.dynamicColumn;
        if (contentElement.scrollWidth >= 450) {
          contentElement.classList.add('scrollable');
        }
      })
    },
    openForm(data, row, title, type) {
      if (type === '1') {
        this.list = evaluateUpperList
        this.list2 = evaluateLowerList
      } else {
        this.list = evaluateUpperList2
        this.list2 = evaluateLowerList2
      }
      this.supplierOptions = data
      this.formInline.supplierCategory = type
      this.title = title
      this.title2 = '类别名称'
      this.title1 = '供应商'
      this.projectList = []
      this.fileList = []
      this.typeTree = [] //清空分类
      this.list.forEach(v => {
        v.value = 0
        v.merkts = ''
      })
      this.list2.forEach(v => {
        v.merkts = ''
      })
      this.formInline.id = ''
      this.formInline.supplierId = ''
      this.formInline.categoryName = ''
      this.formInline.supplierStoreId = ''
      this.formInline.time = []

      if (typeof row === 'object') {
        this.getProjectData(false)
        this.edit(row)
      } else {
        this.getProjectData(true)
        this.categoryList(null,'add')
         this.visible = true
      }
    },
     async onChangeFile(file, fileList) {
       let fileKey = 'evaluate'
       const url = await this.uploadFile({ fileKey: fileKey, data: file });
       if (url) {
        if (file.file.type == 'application/pdf') {
          this.fileList.push({name:file.file.name,url:pdfimg,urls:url,type:1})
        } else {
          this.fileList.push({name:file.file.name,url:url,type:2})
        }
      }
    },
     handlePreview(file) {
      if (file.type == 1) {
        window.open(file.urls)
      } else {
        this.previewUrl = file.url;
        this.dialogVisible = true;
      }
    },
    handleRemove(file, fileList) {
      console.log('--------')
      const index = this.fileList.indexOf(file);
      if (index > -1) {
        this.fileList.splice(index, 1);
      }
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg" ||
        file.type === "application/pdf";
      if (!isJPG) {
        this.$message.error("营业执照只能是 jpeg，png，jpg 格式或pdf格式!");
      }
      return isJPG;
    },
    async edit(row) {
      const regex = /#~#/;
      const { data } = await getSupplierEvaluationPage({ id: row.id })
      this.visible = true
      this.title1 = data.supplierName
      this.title2 = data.categoryName
      this.formInline.id = data.id
      this.categoryList(data,'edit') //获取全部种类 在通过供应商id去匹配 
      let strat = moment(data.evaluationStartDate).format('YYYY-MM-DD');
      let end = moment(data.evaluationEndDate).format('YYYY-MM-DD');
      this.formInline.time = [strat, end]
      this.formInline.supplierId = data.supplierId
      this.formInline.categoryName = data.categoryName
      this.list = JSON.parse(data.processDetail) //投标过程明细
      let objs = JSON.parse(data.deductionDetails); //项目打分明细自定义及头部项目
      this.projectList = objs.projectList
      this.list2 = objs.list2

      //附件赋值
      if (regex.test(data.projectCountInfo)) {
        const parts = data.projectCountInfo.split("#~#");
        this.fileList = JSON.parse(parts[1]);
      } 


    },
    //获取项目列表
    async getProjectData(flag) {
      const { data } = await getProjectOptions()
      if (flag) { //新增默认一个
        this.addDynamicColumn()
      }
     this.projectOptions = data
    },
    //全部种类
     async categoryList(row,type) {
        const { code, data } = await getSupplierCategoryTree();
      if (code == 200) {
       if (data && data.length) {
          let NewData = data.map((ele) => TreeArrar(ele))
         this.treeData = NewData
         if (row) {
          this.supplierChnage(row.supplierId,type)
           this.formInline.supplierStoreId = row.supplierStoreId
         }
       } 
     }
    },
    //供应商id查询种类 并对种类进行匹配组装
    async supplierChnage(e,type) {
      let param = {}
      param.supplierId = e
      param.storeStatus = '1'
      param.isPaused = 0
      param.queryType = "4"
      this.title1 = this.supplierOptions.find(v => v.id == e).name
      const { data } = await getSupplierStorePage(param)
      this.formInline.categoryName = ''
      let result = []
      if (type && type == 'add') { //如何是新增 或者选择需要重置  修改不需要重置。
         this.title2 = '类别名称' //清空已选的种类名称
      }
      data.list.forEach(v => {
        let child = v.applyCategoryId.split(',')
        let ids = result.map(item=>item)
        if (child.length > 1) {
          child.forEach(n => {
            if (!ids.includes(n)) {
              result.push(n)
            }
          })
        } else {
          if (!ids.includes(v.applyCategoryId)) {
            result.push(v.applyCategoryId)
          }
        }
      })

      getSupplierCategoryTree().then(res => {
        let NewData = res.data.map((ele) => TreeArrar(ele))
        this.typeTree = this.matchTree(NewData, result);
      })
     // this.typeTree = this.matchTree(treeData, result);
    },
    matchTree(tree, flatArray) {
      return tree.filter(node => {
        // 检查当前节点是否在一维数组中
        const isMatched = flatArray.some(idx => idx == node.value);

        // 递归检查子节点
        if (node.children && node.children.length > 0) {
          node.children = this.matchTree(node.children, flatArray);
        }

        // 如果当前节点或子节点匹配，则保留该节点
        return isMatched || (node.children && node.children.length > 0);
      });
    },
    //获取中文种类
    typeChange(e) {
      let str = this.getLabelsByValues(this.treeData, e);
      if (str && str.length) {
        this.title2 = str.join(',').replace(/,/g, "/");
      }
    },
    getLabelsByValues(options, values) {
      const labels = [];
      let currentOptions = options;
      // 遍历 values，逐级查找对应的 label
      values.forEach(value => {
        const found = currentOptions.find(option => option.value === value);
        if (found) {
          labels.push(found.label);
          currentOptions = found.children || [];
        }
      });

      return labels;
    },
    //添加
     addDynamicColumn() {
      const newColumn = {
        id: "",
        tdScore: 0,
        prop: `dynamic${this.projectList.length + 1}`
      };
      this.projectList.push(newColumn);
      // 为每一行添加动态列的数据
       this.list2.forEach(row => {
         row[newColumn.prop] = 0;
       });
    },
    //删除
    delProject(index,key) {
      this.projectList.splice(index, 1)
      this.list2.forEach(item => {
        this.$delete(item, key);
      });
    },
    calculateTotal(event, rowIndex) {
      
      const regex = /^(0|[1-9]\d*)(\.\d+)?$/;
      if (!regex.test(event.target.value)) {
        event.target.value = event.target.value.replace(/[^\d.]/g, '');
      }
      // 获取当前行的前 10 个分数
      const keys = this.projectList[rowIndex].prop
      // 计算总分
      let total = new Big(0)
      this.list2.forEach(item => {
        for (let key in item) {
          if (key == keys) {
            const num = parseFloat(item[key]);
            if (!isNaN(num)) {
              total = total.plus(new Big(num));
            }
          }
        }
      });
      // 更新当前行的总分
      this.projectList[rowIndex].tdScore = total.toString();
    },
   async submitAddly() {
      let { formInline,title1,title2,list,list2,projectList } = this
        let param = {}
      if (!formInline.supplierId) {
        return this.$message.error('请选择供应商')
      }
      if (formInline.supplierStoreId.length == 0) {
        return this.$message.error('请选择类别名称')
      }
      if (formInline.time && formInline.time.length == 0) {
        return this.$message.error('请选择考核周期')
      }

      let total1 = new Big(0) //上面部分
     list.forEach(v => {
       if (v.value) {
          const num = parseFloat(v.value);
            if (!isNaN(num)) {
              total1 = total1.plus(new Big(num));
            }
        }
     })
     let total2 = new Big(0) // 下面部分
     let projectCountInfo = [] // 下面部分json

     for (let i = 0; i < projectList.length; i++){
       if (!projectList[i].id) {
         return this.$message.error('请选择项目');
      }
     }

     
     projectList.forEach(item => {
       let link = {}
       link.id = item.id
      link.score = item.tdScore ?? 0
       if (item.tdScore) {
          const num = parseFloat(item.tdScore);
            if (!isNaN(num)) {
              total2 = total2.plus(new Big(num));
            }
       }
       let obj = this.projectOptions.find(v => v.id == item.id)
        link.name = obj&&obj.name ? obj.name : ''
       projectCountInfo.push(link)
       item.id = obj&&obj.id ? obj.id : ''
       item.name = obj&&obj.name ? obj.name : ''
     })

     const combinedObject = {
        projectList: projectList,
        list2: list2
      };


      param.supplierId = formInline.supplierId
     param.supplierName = title1
     param.categoryName = title2

     // 如果是选择的就是数组  修改的就是数字
     if (Array.isArray(formInline.supplierStoreId)) {
       param.supplierStoreId = formInline.supplierStoreId.at(-1)
     } else {
       param.supplierStoreId = formInline.supplierStoreId
     }

     param.evaluationStartDate = formInline.time[0]
      param.evaluationEndDate = formInline.time[1]
     param.supplierCategory = formInline.supplierCategory
     param.totalDeduction = total1.plus(total2).toString();
     param.bidProcessDeduction = total1


       //附件 把附件放在项目里面  
     if (this.fileList && this.fileList.length) {

      param.projectCountInfo = JSON.stringify(projectCountInfo) + '#~#' + JSON.stringify(this.fileList)
     } else {
      param.projectCountInfo = JSON.stringify(projectCountInfo)
     }


     let evaluationConclusion = ''
     if (param.totalDeduction >= 5 && param.totalDeduction < 10) {
        evaluationConclusion = '扣分达到5分，给予警告，并暂停三个月投标资格；'
     }
     if (param.totalDeduction >= 10 && param.totalDeduction < 20) {
        evaluationConclusion = '扣分达到10分，移出公司供应商库；'
     }
     if (param.totalDeduction >= 20) {
        evaluationConclusion = '扣分达20分的或因供应商原因出现廉洁、安全问题的，移出供应商库并在3年内不得入库；'
     }
     param.evaluationConclusion = evaluationConclusion

     param.processDetail = JSON.stringify(list) //投标过程明细
     param.deductionDetails = JSON.stringify(combinedObject); //项目打分明细自定义及头部项目

     if (this.formInline.id) {
      param.id = this.formInline.id
     }

     const { code } = await getEvaluationSave(param)
     if (code == 200) {
        this.visible = false
        this.$emit('onOk',true)
      }
    }
  }
};
</script>
<style scoped>

.columns-container {
  display: flex;
  min-width: 100%;
  margin-top: 10px;
}
.column1{
  width: 70px;
  padding-bottom: 8px;
}
.column1-content{
  height: 70px;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
    align-items: center;
    justify-content: center;
}
.column1 > :nth-child(3){
  height: 70px;
}
.column1 > :nth-child(4){
  height: 70px;
}
.column1 > :nth-child(5){
  height: 53px;
}


.column2{
  flex: 1;
  padding-bottom: 8px;
}
.column-contentp-rowspan{
  flex-grow: 1;
  display: flex;
}
.col1{
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #f0f0f0;
}
.col1 li {
  width: 100px;
  background-color: #fafafa;
}
.col1 li:nth-child(1){
  flex: 1;
  display: flex;
    justify-content: center;
    align-items: center;
    
}
.col1 li:nth-child(2){
  text-align: center;
  border-top: 1px solid #f0f0f0;
  height: 70px;
  line-height: 70px;
}
.col1 li:nth-child(3){
  text-align: center;
  border-top: 1px solid #f0f0f0;
  height: 70px;
  line-height: 70px;
}
.col2{
  list-style: none;
  margin: 0;
  padding: 0;
  flex: 1;
}
.col2 li{
  padding: 10px;
  height: 70px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: center;
  flex-direction: column;
}
.col2 li:nth-child(2){
  height: 70px;
  line-height: 18px;
}
.col2 li:nth-child(3){
  height: 70px;
  line-height: 18px;
}
.col2 li:nth-child(4){
  height: 53px;
  line-height: 18px;
}



.column3{
  width: 200px;
  padding-bottom: 8px;
}
.column3-content{
  height: 70px;
  padding: 10px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
    align-items: center;
    justify-content: center;
}
.column3 > :nth-child(3){
  height: 70px;
}
.column3 > :nth-child(4){
  height: 70px;
}
.column3 > :nth-child(5){
  height: 53px;
}

.dynamic-header{
  position: relative;
  text-align: center;
}
.dynamic-header::before{
  content: '';
  background:#f0f0f0;
  height: 1px;
  position: absolute;
  left: -10px;
  right: -10px;
  top: 38px;
}
.dynamic-content{
  list-style: none;
  margin: 0;
  padding: 0;
}
.dynamic-content li {
  padding: 10px;
  height: 70px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: center;
  flex-direction: column;
}
.dynamic-content li:nth-child(2){
  height: 70px;
}
.dynamic-content li:nth-child(3){
  height: 70px;
}
.dynamic-content li:nth-child(4){
  height: 53px;
}



.column {
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
  border: 1px solid #f0f0f0;
  border-right: 0;
}
.column:last-child{
  border-right: 1px solid #f0f0f0;
}

.column-box::-webkit-scrollbar {
  height: 8px;
  scrollbar-gutter: stable;
}

.column-box{
  overflow-x: auto;
  display: flex;
}
.scrollable{
  width:450px;
}

.dynamic-column {
  width: 150px;
  flex-grow: 1;
}

.column-header{
  padding: 10px;
  background-color: #fafafa;
  border-bottom: 1px solid #f0f0f0;
      display: flex;
    align-items: center;
    justify-content: center;
    height: 85px;
}

.column-footer {
  background: rgb(167, 16, 72);
  border-bottom: none;
  border-top: 1px solid #f0f0f0;
  height: 38px;
    color: #fff;
    line-height: 38px;
    text-align: center;
}

.column-content {
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
    align-items: center;
    justify-content: center;
}


</style>
<style scoped>
.custom-other-table{
  min-height: 25px;
    width: 100%;
    text-align: left;
    border-collapse: collapse;
}
.custom-other-table tr td {
    border: 1px solid #f0f0f0;
    color: rgba(0, 0, 0, .85);
    font-weight: normal;
    font-size: 14px;
    padding: 10px;
}
.btm10{
  margin-top: 20px;
}
.line{
  display: block;
  padding-top: 10px;
  margin-top: 10px;
}
.tr-title {
    background-color: #fafafa;
    text-align: center;
}
.f1{
  width: 70px;
}
.f2{
    width: 100px;
}
.f3{
  width: 130px;
}
.f4{
  width: 200px;
}
.fn{
  padding: 0 !important;
}
.btns{
  font-size: 18px;
    margin-left: 6px;
    vertical-align: text-top;
    cursor: pointer;
}
.btns:hover{
  color: rgba(64,158,255,0.8)
}
.sumot-input{
  min-height: 30px;
    height: 30px;
    display: block;
    resize: vertical;
    padding: 5px 15px;
    line-height: 1.5;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    width: 100%;
    font-size: inherit;
    color: #606266;
    background-color: #FFF;
    background-image: none;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    -webkit-transition: border-color .2scubic-bezier(.645,.045,.355,1);
    transition: border-color .2scubic-bezier(.645,.045,.355,1);
}

.mot-li{
  margin: 0;
  padding: 0;
  list-style: none;
  display: flex;
  align-items: center;
}
.mot-li li{
  border-right: 1px solid #f0f0f0;
  width: 150px;
}
.mot-li li:last-child{
  border-right: 0;
}
.mot-inner{
  padding: 10px;
}
</style>
